package com.cote.douhahou.pretloan.utils;

import static com.cote.douhahou.pretloan.home.PersonalCenterFragment.User_Avatar;
import static com.cote.douhahou.pretloan.utils.AkomapaLendConfigs.*;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import androidx.core.content.ContextCompat;

import com.cote.douhahou.pretloan.beans.PermissAkomapalendionInfo;
import com.cote.douhahou.pretloan.beans.PersAkomapalendonalInfo;
import com.cote.douhahou.pretloan.launcher.BaseContext;
import com.cote.douhahou.pretloan.R;
import com.cote.douhahou.pretloan.url.AkomapalendPaths;

import org.jetbrains.annotations.NotNull;

import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AkomapaLendUtil {

    public static void akomapaLendRun(Runnable runnable,int i){
        if (i>0) runnable.run();
        else akomapaLendRun(runnable);
    }

    private static void akomapaLendRun(Runnable runnable){
        runnable.run();
    }

    public static void akomapalendInit(Context context){

        parsePermissionInfoList(context);
        initSp();

    }

    public static String aesEncrypt(String msg) {

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(
                    Cipher.ENCRYPT_MODE,
                    new SecretKeySpec(AesKey.getBytes(StandardCharsets.UTF_8), "AES"),
                    new IvParameterSpec(AesIv.getBytes(StandardCharsets.UTF_8))
            );

            return Base64.encodeToString(cipher.doFinal(msg.getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT | Base64.NO_WRAP);
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    public static String aesDecryptDefault(String encryptedMessage) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            cipher.init(
                    Cipher.DECRYPT_MODE,
                    new SecretKeySpec(AesKey.getBytes(StandardCharsets.UTF_8), "AES"),
                    new IvParameterSpec(AesIv.getBytes(StandardCharsets.UTF_8))
            );

            return new String(cipher.doFinal(Base64.decode(encryptedMessage, Base64.DEFAULT | Base64.NO_WRAP)), StandardCharsets.UTF_8);

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String frontWord;
    public static String mobileCode;
    public static String pam = "";

    public static String front() {
        if (TextUtils.isEmpty(frontWord)) return "";
        return frontWord;
    }

    public static boolean frontIsEmpty(){
        return TextUtils.isEmpty(frontWord) || frontWord.length()<=1;
    }

    public static void frontFormat(String front) {
        AkomapaLendUtil.frontWord = "/"+ front;
    }

    public static String commonUrl(){
        if (TextUtils.isEmpty(frontWord)) return "";
        return AkomapalendPaths.BasePath + front()+ AkomapalendPaths.CommonPath;
    }

    public static void mobileCode(String areaCode) {
        AkomapaLendUtil.mobileCode = areaCode;
        mSp.edit().putString(KeyAreaCode, AkomapaLendUtil.mobileCode).apply();
    }

    public static String mobileCode() {
        if (TextUtils.isEmpty(mobileCode)) return "";
        if (mobileCode.startsWith("+")) return mobileCode;
        return "+"+ mobileCode;
    }

    public static boolean isGh(){
        return CodeGh.endsWith(mobileCode());
    }

    public static boolean isCt(){
        return CodeCote.endsWith(mobileCode());
    }

    public static boolean isUg(){
        return CodeUg.endsWith(mobileCode());
    }

    public static boolean isCm(){
        return CodeCa.endsWith(mobileCode());
    }

    public static boolean isSen(){
        return CodeSen.endsWith(mobileCode());
    }

    public static boolean isTsBindAccount(){
        return isCt()|| isCm()|| isSen();
    }

    public static boolean isRepayType1(){
        return isUg();
    }

    public static boolean isRepayType2(){
        return !isRepayType1();
    }

    public static void parsePermissionInfoList(Context context){

        PermissionInfoList.clear();

        if (!smsPermissionHasAgree(context))
            PermissionInfoList.add(new PermissAkomapalendionInfo(R.drawable.image_sms_white,R.drawable.icon_sms,
                    context.getString(R.string.permission_sms_title),context.getString(R.string.permission_sms_text)
                    , PermissionSms));

        if (!phonestatePermissionHasAgree(context))
            PermissionInfoList.add(new PermissAkomapalendionInfo(R.drawable.image_phone_3,R.drawable.image_phone_white,
                    context.getString(R.string.permission_phone_title),context.getString(R.string.permission_phone_text)
                    , PermissionPhone));

    }

    public static boolean startPermissionHasAgree(Context context){
        for (String permission: PermissionArrStart){
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context,permission)) return false;
        }
        return true;
    }

    public static boolean permissionsHasAgree(Context context, String... permissions){
        for (String permission:permissions){
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context,permission)) return false;
        }
        return true;
    }

    public static boolean phonestatePermissionHasAgree(Context context){
        return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(context, PermissionPhone);
    }

    public static boolean smsPermissionHasAgree(Context conte){
        return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(conte, PermissionSms);
    }

    public static String State = "No_State";

    public static boolean stateIsChange(String newState){
        if (newState.equalsIgnoreCase(State)) return false;

        //状态:还款 -> 无订单  经验+10
        if (State.equalsIgnoreCase(StateREpay) && newState.equalsIgnoreCase(StateNoORder)){
            PersAkomapalendonalInfo.instance().addExpValue(10);
            PersAkomapalendonalInfo.instance().uploadUserInfo(null,null);
        }

        State = newState;
        return true;
    }

    public static void clearState(){
        State = "No_State";
    }

//---------------------------------------本地存储-----------------------------

    public static SharedPreferences mSp;
    public static String spMobile;
    public static String spToken;
    public static String spUSerId;
    public static boolean spIsAdSource;

    public static int spRateCount;
    public static int spRateCount_Active;


    public static void initSp(){

        mSp = BaseContext.instance().getSharedPreferences(packageName(), Context.MODE_PRIVATE);
        AkomapaLendUtil.spMobile = mSp.getString(KeyPhone, "");
        AkomapaLendUtil.spToken = mSp.getString(KeyToken, "");
        AkomapaLendUtil.spUSerId = mSp.getString(KeyUserID, "");
        AkomapaLendUtil.spIsAdSource = mSp.getBoolean(KeyAdSource,false);
        AkomapaLendUtil.mobileCode = mSp.getString(KeyAreaCode,"");
        spRateCount = mSp.getInt(KeyRateCount,0);
        spRateCount_Active = mSp.getInt(KeyRateCount_Active,0);

    }

    public static boolean hasLogin() {
        return !TextUtils.isEmpty(AkomapaLendUtil.spToken);
    }

    public static String mobile() {
        if (TextUtils.isEmpty(spMobile)) spMobile ="";
        return spMobile;
    }

    public static String mobile1(){
        if (TextUtils.isEmpty(spMobile)) spMobile ="";
        int length = spMobile.length();
        return "***"+ spMobile.substring(length-4,length);
    }

    @SuppressLint("ApplySharedPref")
    public static void sMobile(String mobile) {
        AkomapaLendUtil.spMobile = mobile;
        mSp.edit().putString(KeyPhone, AkomapaLendUtil.spMobile).commit();
    }

    public static String token() {
        if (TextUtils.isEmpty(spToken)) spToken = "";
        return spToken;
    }

    public static String userId() {
        if (TextUtils.isEmpty(spUSerId)) spUSerId = "";
        return spUSerId;
    }

    @SuppressLint("ApplySharedPref")
    public static void sToken(String token) {
        AkomapaLendUtil.spToken = token;
        mSp.edit().putString(KeyToken, AkomapaLendUtil.spToken).commit();
    }

    @SuppressLint("ApplySharedPref")
    public static void sUserId(String userId) {
        AkomapaLendUtil.spUSerId = userId;
        mSp.edit().putString(KeyUserID, AkomapaLendUtil.spUSerId).commit();
    }

    public static boolean adSource(){
        return true;
//        return isAdSource;
    }

    @SuppressLint("ApplySharedPref")
    public static void sIsAdSource(boolean isAdSource){
        AkomapaLendUtil.spIsAdSource = isAdSource;
        mSp.edit().putBoolean(KeyAdSource,isAdSource).commit();
    }

    public static int rateCount() {
        return spRateCount;
    }

    public static int rateCount_Active() {
        return spRateCount_Active;
    }

    @SuppressLint("ApplySharedPref")
    public static void addRateCount(){
        spRateCount++;
        mSp.edit().putInt(KeyRateCount, spRateCount).commit();
    }

    @SuppressLint("ApplySharedPref")
    public static void addRateCount_Active(){
        spRateCount_Active++;
        mSp.edit().putInt(KeyRateCount_Active, spRateCount_Active).commit();
    }

    public static void clearSp(){
        sMobile("");
        sUserId("");
        sToken("");
        User_Avatar = null;
    }

    @NotNull
    public static String packageName() {
        String pckName = BaseContext.instance().getPackageName();
        if (TextUtils.isEmpty(pckName)) {
            pckName = AkomapaLendConfigs.PackageName;
        }
        return pckName;
    }

    public static Bitmap circleBitmap(Bitmap bitmap) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final Paint paint = new Paint();
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);

        // 绘制圆形边框
        canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);

        // 使用SRC_IN模式，保留原图像与遮罩交集的部分
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rectF, paint);

        return output;
    }


    public static int deviceScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        return metrics.widthPixels;
    }

    public static int deviceScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        return metrics.heightPixels;
    }

    public static int sizeDp2Px(Context context, float dpValue){
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int sizePx2Dp(Context context, float pxValue){
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }





}
